"""
学习路径相关
"""

import os
import logging
import time
import traceback
import datetime
import random

from alipay import AliPay
from flask import Blueprint, request, g, make_response, send_from_directory

from flask_restful import Resource, Api, reqparse, marshal, fields, current_app
from sqlalchemy import or_, and_, not_
from werkzeug.utils import secure_filename

from common.models import rds, db, cache
from common.models.user import UserBase
from common.models.course import Course
from common.models.study_path import Path, Stage, CourseStage
from common.utils.custom_output_json import custom_output_json
from common.model_fields.course import stage_fields, path_fields, stage_info_fields
from common.utils.login_util import login_required
from common.utils.utils import get_upload_token, check_is_manager

path_bp = Blueprint('path_bp', __name__, url_prefix='/path')
api = Api(path_bp)


@api.representation('application/json')
def output_json(data, code=200, headers=None):
    return custom_output_json(data, code, headers)


class AddStudyPath(Resource):
    """
    添加学习路径
    """
    @login_required
    def post(self):
        user_id = g.user_id
        # 管理员有权限添加学习路径
        user = UserBase.query.get(user_id)
        if user.is_superuser == 0:
            return {'message': '无权限'}, 500

        # 添加学习路径
        parser = reqparse.RequestParser()
        parser.add_argument('title', required=True)
        parser.add_argument('img', default='')
        parser.add_argument('desc', required=True)

        args = parser.parse_args()
        title = args.get('title')
        img = args.get('img')
        desc = args.get('desc')

        # 验证数据是否合法
        if len(title) > 16:
            return {'message': '标题过长'}, 400
        if len(desc) > 265:
            return {'message': '描述过长'}, 400
        try:
            # 验证此学习路径是否存在   存在 返回 错误信息     不存在，正常添加
            path_count = Path.query.filter_by(title=title).count()
            if path_count >= 1:
                return {'message': '此学习路径已存在'}, 407

            path = Path(title=title, img=img, desc=desc, user_id=user_id)
            db.session.add(path)
            db.session.commit()
            return {'message': 'ok'}
        except:
            error = traceback.format_exc()
            msg = 'AddStudyPath is error:{}'.format(error)
            logging.error(msg)
            return {'message': msg}, 500


class AddStage(Resource):
    """
    添加学习阶段
    """
    @login_required
    def post(self):
        user_id = g.user_id
        # 获取当前登录用户的id:
        user = UserBase.query.get(user_id)
        # 判断该用户有没有添加的权限
        if user.is_superuser == 0:
            return {'message': '无权限！', 'code': 503}
        # 获取参数
        parse = reqparse.RequestParser()
        parse.add_argument('title')
        parse.add_argument('serial_num', default=10)
        parse.add_argument('path_id', required=True)
        args = parse.parse_args()
        title = args.get('title')
        serial_num = args.get('serial_num')
        path_id = args.get('path_id')
        path = Path.query.get(path_id)
        # 判断该学习路径是否存在
        if not path:
            return {'message': '该学习路径不存在！', 'code': 506}
        # 判断当前要添加的学习阶段名是否已存在
        if len(title) > 16:
            return {'message': '阶段名过长'}, 406
        stage_name = Stage.query.filter_by(path=path_id, title=title).count()
        if stage_name >= 1:
            return {'message': '该学习路径的阶段已存在'}, 507
        stage = Stage(title=title, serial_num=serial_num, path=path_id, user_id=user_id)
        db.session.add(stage)
        db.session.commit()
        return marshal(stage, stage_fields)


class AddStageCourse(Resource):
    """
    添加阶段课程
    """
    @login_required
    def post(self):
        user_id = g.user_id
        # 检查用户权限
        is_manager = check_is_manager(user_id)
        if not is_manager:
            return {'message': '无权限'}, 503
        parse = reqparse.RequestParser()
        parse.add_argument('stage_id', required=True)
        parse.add_argument('course_id', required=True)
        args = parse.parse_args()
        stage_id = args.get('stage_id')
        course_id = args.get('course_id')

        # 检查数据是否合理
        stage = Stage.query.get(stage_id)
        if not stage:
            return {'message': '阶段数据错误'}, 507
        course = Course.query.get(course_id)
        if not course:
            return {'message': '课程数据错误'}, 508

        stage_course = CourseStage.query.filter_by(course=course_id, stage=stage_id).count()
        if stage_course >= 1:
            return {'message': '当前数据已存在'}, 509
        stage_course = CourseStage(course=course_id, stage=stage_id)
        db.session.add(stage_course)
        db.session.commit()
        return {'message': '添加成功'}, 200


class GetPath(Resource):
    """
    获取学习路径
    """
    def get(self):
        path_list = Path.query.order_by(Path.id.desc()).all()

        path_list = marshal(path_list, path_fields)
        for path in path_list:
            path.update({'section_sum': random.randint(100, 999)})

        return path_list


class GetPathInfo(Resource):
    """
    获取学习路径的详细信息
    """

    def _get_course_data(self, course_id_list):
        """
        获取课程的详细数据
        :param course_id:
        :return:
        """
        result = []
        print('111111111111', course_id_list)
        for course in course_id_list:
            course = Course.query.get(course.id)
            result.append(course.to_json())
        return result


    def get(self):
        parse = reqparse.RequestParser()
        parse.add_argument('pid', required=True)
        args = parse.parse_args()
        pid = args.get('pid')

        path = Path.query.get(pid)
        if not path:
            return {'message': '此学习路径不存在'}, 504
        path = marshal(path, path_fields)
        path.update({'section_sum': random.randint(100, 999)})

        stage_list = Stage.query.filter_by(path=pid).all()
        new_stage_list = []
        for stage in stage_list:
            new_stage = marshal(stage, stage_info_fields)
            coursedata = {'coursedata': self._get_course_data(stage.course_list)}
            new_stage.update(coursedata)
            new_stage_list.append(new_stage)

        result = {
            'path_info': path,
            'stage_info': new_stage_list
        }
        return result


api.add_resource(AddStudyPath, '/add_study_path', endpoint='add_study_path')
api.add_resource(AddStage, '/add_stage', endpoint='add_stage')
api.add_resource(AddStageCourse, '/add_course_stage', endpoint='add_course_stage')
api.add_resource(GetPath, '/get_path', endpoint='get_path')
api.add_resource(GetPathInfo, '/get_path_info', endpoint='get_path_info')
